package cog.support.springmvc.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * 公共异常处理
 * 
 * @author 陈杰
 * @sine 2016年9月19日 18:49:06
 * @version v0.1
 * 
 * Copyright DongHui(chenjie_java@aliyun.com)
 */
public class ColltrollerException implements HandlerExceptionResolver{
    private Logger logger = LoggerFactory.getLogger(ColltrollerException.class);

	@ResponseBody
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception){
        logger.debug("控制器出现异常:",exception);
        if(handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod)handler;
            ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
            if(responseBody != null ){
                PrintWriter printWriter = null;
                try{
                    printWriter = response.getWriter();
                    printWriter.write("{status}");
                    printWriter.flush();
                }catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    if(printWriter!=null) printWriter.close();
                }
            }
        }
        return null;
	}

}
